package dmxGroupControl;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.TreeSet;
import java.util.stream.Collectors;

import org.jdom2.Element;


public class ChannelCollection extends TreeSet<Channel>
{
	/**
     * 
     */
    private static final long serialVersionUID = -6331621888304066152L;
	
	public ChannelCollection()
	{
	    super();
	}
	
	public ChannelCollection(int channelStart, Element fixtureDefinitionElement)
	{
		this();
		LoadFromFixtureDefinition(channelStart, fixtureDefinitionElement);
	}
	
	public void OptionalSetChannel(String channelName, float value)
    {
        if(Contains(channelName))
        {
            GetChannel(channelName).SetValue(value);
        }
    }
	
	public Channel GetChannel(String channelName)
    {
        for (Channel channel : this)
        {
            if (channel.GetName().compareToIgnoreCase(channelName) == 0)
            {
                return channel;
            }
        }
        return null;
    }
    
    public float OptionalGetChannel(String channelName)
    {
        if(Contains(channelName))
        {
            return GetChannel(channelName).GetValue();
        }
        else
        {
            return 0.0f;
        }
    }
	
	public boolean Contains(String channelName)
    {
        return GetChannel(channelName) != null;
    }

	public void Add(Channel channel)
	{
		add(channel);
	}
	
	public void Remove(Channel channel)
	{
		remove(channel);
	}
	
	public Channel GetFirst()
	{
		return first();
	}
	
	public Channel GetLast()
    {
        try
        {
            return last();
        }
        catch (NoSuchElementException e)
        {
            e.printStackTrace();
            return null;
        }
    }
	
	
	public void Clear()
	{
		clear();
	}

	public void Reposition(int amount)
	{
	    for(Channel channel : this)
	    {
	        channel.SetDMXChannel(channel.GetDMXChannel() + amount);
	    }
	}

	public void LoadFromFixtureDefinition(int channelStart, Element fixtureDefinitionElement)
	{
		for (Element entry : fixtureDefinitionElement.getChildren("channel"))
        {
	        String channelName = entry.getAttributeValue("name");
	        int dmx = Integer.parseInt(entry.getAttributeValue("dmx"));
            int min = Integer.parseInt(entry.getAttributeValue("min"));
            int max = Integer.parseInt(entry.getAttributeValue("max"));
            Channel channel = new Channel(channelName, min, max, dmx + channelStart - 1);
            Add(channel);
        }
	}

    public List<String> toStrings()
    {
        return this.stream().map(Channel::GetName).collect(Collectors.toList());
    }
}
